package org.dromara.Nyt7PolicyInsurance.service.impl;

import cn.hutool.core.bean.BeanUtil;
import org.dromara.Nyt7PolicyInsurance.domain.vo.Nyt7PolicyInsuranceCountVo;
import org.dromara.Nyt7PolicyInsurance.domain.vo.Nyt7PolicyInsuranceSearchVo;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.dromara.utils.utils.UserUtil;
import org.springframework.stereotype.Service;
import org.dromara.Nyt7PolicyInsurance.domain.bo.Nyt7PolicyInsuranceBo;
import org.dromara.Nyt7PolicyInsurance.domain.vo.Nyt7PolicyInsuranceVo;
import org.dromara.Nyt7PolicyInsurance.domain.Nyt7PolicyInsurance;
import org.dromara.Nyt7PolicyInsurance.mapper.Nyt7PolicyInsuranceMapper;
import org.dromara.Nyt7PolicyInsurance.service.INyt7PolicyInsuranceService;

import java.util.*;

/**
 * 保单查询Service业务层处理
 *
 * @author Lion Li
 * @date 2025-01-09
 */
@RequiredArgsConstructor
@Service
public class Nyt7PolicyInsuranceServiceImpl implements INyt7PolicyInsuranceService {

    private final Nyt7PolicyInsuranceMapper baseMapper;
    private final UserUtil userUtil;

    /**
     * 查询保单查询
     *
     * @param id 主键
     * @return 保单查询
     */
    @Override
    public Nyt7PolicyInsuranceVo queryById(Long id){
        return baseMapper.selectVoByIdEx(id);
    }

    /**
     * 分页查询保单查询列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 保单查询分页列表
     */
    @Override
    public TableDataInfo<Nyt7PolicyInsuranceVo> queryPageList(Nyt7PolicyInsuranceBo bo, PageQuery pageQuery) {
        Page<Object> build = pageQuery.build();
        Page<Nyt7PolicyInsuranceVo> page = new Page<>(build.getCurrent(),build.getPages());

        String postName = userUtil.getPostName();

        List<Nyt7PolicyInsurance> policyInsurances = baseMapper.selectEx();
        List<Nyt7PolicyInsuranceVo> convert = BeanUtil.copyToList(policyInsurances, Nyt7PolicyInsuranceVo.class);
        List<Nyt7PolicyInsuranceVo> list = new ArrayList<>();
        if (convert != null) {
            list = convert.stream()
                .filter(nyt7PolicyInsuranceVo -> {
                    boolean idMatch = true,longitudeMatch = true,latitudeMatch = true,nameMatch = true,postNameMatch = true;
                    if(bo.getPolicyNumber() != null)
                        idMatch = Objects.equals(nyt7PolicyInsuranceVo.getPolicyNumber(), bo.getPolicyNumber());
                    if(bo.getLongitude() != null)
                        longitudeMatch = Objects.equals(nyt7PolicyInsuranceVo.getPlotDetailInfo().getLongitude(), bo.getLongitude());
                    if(bo.getLatitude() != null)
                        latitudeMatch = Objects.equals(nyt7PolicyInsuranceVo.getPlotDetailInfo().getLatitude(), bo.getLatitude());
                    if(bo.getInsuranceCompanyName() != null)
                        nameMatch = Objects.equals(nyt7PolicyInsuranceVo.getSysPost().getPostName(), bo.getInsuranceCompanyName());
                    if(postName != null){
                        postNameMatch = Objects.equals(nyt7PolicyInsuranceVo.getSysPost().getPostName(), postName);
                    }
                    return idMatch && longitudeMatch && latitudeMatch && nameMatch && postNameMatch;
                })
                .toList();
        }

        page.setRecords(list);

        return TableDataInfo.build(page);
    }

    @Override
    public List<Nyt7PolicyInsuranceVo> queryListAll() {

        List<Nyt7PolicyInsurance> policyInsurances = baseMapper.selectEx();
        List<Nyt7PolicyInsuranceVo> convert = BeanUtil.copyToList(policyInsurances, Nyt7PolicyInsuranceVo.class);
        if (convert != null){
            convert.stream().map(Nyt7PolicyInsuranceVo::getPlotDetailInfo).forEach(info -> info.setCity(info.getDistrictCounty()));
        }

        if (convert != null && !convert.isEmpty()) {
            mergeByCity(convert);
        }

        List<Nyt7PolicyInsuranceVo> vos = BeanUtil.copyToList(policyInsurances, Nyt7PolicyInsuranceVo.class);
        if (!vos.isEmpty()) {
            mergeByCity(vos);
        }
        if (convert != null) {
            convert.addAll(vos);
        }

        String postName = userUtil.getPostName();
        if (postName != null) {
            if (convert != null) {
                convert = convert.stream()
                    .filter(nyt7PolicyInsuranceVo -> Objects.equals(nyt7PolicyInsuranceVo.getSysPost().getPostName(), postName))
                    .toList();
            }
        }
        return convert;
    }

    private void mergeByCity(List<Nyt7PolicyInsuranceVo> convert) {
        List<Nyt7PolicyInsuranceVo> removeList = new ArrayList<>();
        Map<String, Nyt7PolicyInsuranceVo> map = new HashMap<>();
        for (Nyt7PolicyInsuranceVo nyt7PolicyInsurance : convert) {
            String city = nyt7PolicyInsurance.getPlotDetailInfo().getCity();
            if (map.containsKey(city)) {
                Nyt7PolicyInsuranceVo nyt7PolicyInsurance1 = map.get(city);
                nyt7PolicyInsurance1.addFields(nyt7PolicyInsurance);

                removeList.add(nyt7PolicyInsurance);
            } else {
                map.put(city, nyt7PolicyInsurance);
            }
        }
        convert.removeAll(removeList);
    }

    /**
     * 查询符合条件的保单查询列表
     *
     * @param bo 查询条件
     * @return 保单查询列表
     */
    @Override
    public List<Nyt7PolicyInsuranceVo> queryList(Nyt7PolicyInsuranceBo bo) {
        LambdaQueryWrapper<Nyt7PolicyInsurance> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<Nyt7PolicyInsurance> buildQueryWrapper(Nyt7PolicyInsuranceBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<Nyt7PolicyInsurance> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getPolicyNumber()), Nyt7PolicyInsurance::getPolicyNumber, bo.getPolicyNumber());
        return lqw;
    }

    /**
     * 新增保单查询
     *
     * @param bo 保单查询
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(Nyt7PolicyInsuranceBo bo) {
        Nyt7PolicyInsurance add = MapstructUtils.convert(bo, Nyt7PolicyInsurance.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
//        if (flag) {
//            bo.setId(add.getId());
//        }
        return flag;
    }

    /**
     * 修改保单查询
     *
     * @param bo 保单查询
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(Nyt7PolicyInsuranceBo bo) {
        Nyt7PolicyInsurance update = MapstructUtils.convert(bo, Nyt7PolicyInsurance.class);

        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(Nyt7PolicyInsurance entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 校验并批量删除保单查询信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteByIds(ids) > 0;
    }

    @Override
    public List<Nyt7PolicyInsuranceCountVo> getCountByCompany() {
        List<Nyt7PolicyInsurance> policyInsurances = baseMapper.selectEx();
        List<Nyt7PolicyInsuranceCountVo> countVos = new ArrayList<>();
        if (!policyInsurances.isEmpty()) {
            Map<String, Nyt7PolicyInsuranceCountVo> map = new HashMap<>();
            for (Nyt7PolicyInsurance nyt7PolicyInsurance : policyInsurances) {
                Nyt7PolicyInsuranceCountVo vo = new Nyt7PolicyInsuranceCountVo();
                String postName = nyt7PolicyInsurance.getSysPost().getPostName();
                if (map.containsKey(postName)) {
                    vo = map.get(postName);
                    vo.setCount(vo.getCount() + 1);
                } else {
                    map.put(postName, vo);
                    vo.setCompany(postName);
                    vo.setCount(1);
                    countVos.add(vo);
                }
            }
        }

        // 使用 Lambda 表达式对 countVos 按照 count 进行降序排序
        countVos.sort((o1, o2) -> o2.getCount().compareTo(o1.getCount()));

        // 返回前十个元素
        return countVos.size() > 10 ? countVos.subList(0, 10) : countVos;
    }


    @Override
    public Long getCount() {
        return baseMapper.selectCount(null);
    }

    @Override
    public List<Nyt7PolicyInsuranceSearchVo> searchEntityFarmer(String str) {

        List<Nyt7PolicyInsuranceSearchVo> nyt7PolicyInsuranceSearchVos = baseMapper.searchEntityFarmer(str);
        System.out.println();
        return nyt7PolicyInsuranceSearchVos;
    }

    @Override
    public List<Nyt7PolicyInsuranceSearchVo> searchEntityPlot(String str) {

        List<Nyt7PolicyInsuranceSearchVo> nyt7PolicyInsuranceSearchVos = baseMapper.searchEntityPlot(str);
        System.out.println();
        return nyt7PolicyInsuranceSearchVos;
    }







    /**
     * 根据ID列表查询保单查询列表
     *
     * @param ids ID列表
     * @return 保单查询列表
     */
    @Override
    public List<Nyt7PolicyInsuranceVo> queryListByIds(List<Long> ids) {
        LambdaQueryWrapper<Nyt7PolicyInsurance> lqw = Wrappers.lambdaQuery();
        lqw.in(Nyt7PolicyInsurance::getId, ids);
        return baseMapper.selectVoList(lqw);
    }

}
